<template>
  <div class="checkout">
    <van-nav-bar
      title="确认订单"
      left-arrow
      @click-left="$router.push('/cart')"
      fixed
    />
    
    <div class="content" style="padding-top: 46px; padding-bottom: 50px;">
      <!-- 收货地址 -->
      <van-contact-card
        type="add"
        add-text="添加收货地址"
        @click="showAddressPopup = true"
      />

      <!-- 商品列表 -->
      <van-card
        v-for="item in cartList"
        :key="item.id"
        :num="item.quantity"
        :price="item.price"
        :title="item.title"
        :thumb="item.image"
      />

      <!-- 优惠券 -->
      <van-cell-group>
        <van-cell title="优惠券" is-link value="暂无可用"/>
        <van-field
          v-model="remark"
          label="备注"
          type="textarea"
          placeholder="请输入备注"
          rows="1"
          autosize
        />
      </van-cell-group>

      <!-- 价格详情 -->
      <van-cell-group title="价格详情">
        <van-cell title="商品总价" :value="`¥${totalPrice}`"/>
        <van-cell title="运费" value="¥0.00"/>
        <van-cell title="实付金额" :value="`¥${totalPrice}`" size="large"/>
      </van-cell-group>
    </div>

    <!-- 提交订单栏 -->
    <van-submit-bar
      :price="totalPrice * 100"
      button-text="提交订单"
      @submit="onSubmit"
    />

    <!-- 地址编辑弹出层 -->
    <van-popup v-model="showAddressPopup" position="bottom">
      <van-address-edit
        :area-list="areaList"
        show-postal
        show-delete
        show-set-default
        show-search-result
        :search-result="searchResult"
        @save="onSaveAddress"
        @delete="onDeleteAddress"
      />
    </van-popup>
  </div>
</template>

<script>
import { mapState } from 'vuex'
import { areaList } from '@vant/area-data'

export default {
  name: 'Checkout',
  data() {
    return {
      showAddressPopup: false,
      searchResult: [],
      areaList,
      remark: ''
    }
  },
  computed: {
    ...mapState({
      cartList: state => state.cartList
    }),
    totalPrice() {
      return this.cartList.reduce((total, item) => {
        return total + item.price * item.quantity
      }, 0)
    }
  },
  methods: {
    onSaveAddress(content) {
      this.showAddressPopup = false
      // 这里可以保存地址信息
      console.log('save address', content)
    },
    onDeleteAddress() {
      this.showAddressPopup = false
      // 这里可以删除地址信息
    },
    onSubmit() {
      this.$dialog.confirm({
        title: '提交订单',
        message: '是否确认提交订单？'
      }).then(() => {
        // 这里可以提交订单
        this.$toast.success('下单成功')
        this.$router.push('/order')
      }).catch(() => {
        // 取消订单
      })
    }
  }
}
</script>

<style scoped>
.content {
  background-color: #f7f8fa;
}
.van-contact-card {
  margin-bottom: 10px;
}
.van-card {
  background-color: #fff;
}
</style> 